﻿#define _CRT_SECURE_NO_WARNINGS
#include"SList.h"


//打印
void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d-> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

SLTNode* BuyNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTDataType));
	if (newnode == NULL)
	{
		printf("malloc");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
//尾插
void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* Newnode = BuyNode(x);
	//一开始为空要特殊判断
	if (*pphead == NULL)
	{
		*pphead = Newnode;
	}
	else
	{
		//定义个节点找到尾节点才能尾插
		SLTNode* plist = *pphead;

		while (plist->next)
		{
			plist = plist->next;
		}
		plist->next = Newnode;

	}
}

//头插
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* Newnode = BuyNode(x);
	Newnode->next = *pphead;
	*pphead = Newnode;
}
//尾删
void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);

	//二级指针要小心
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* plist = *pphead;
		SLTNode* priv = NULL;
		while (plist->next)
		{
			priv = plist;
			plist = plist->next;
		}
		priv->next = NULL;
		free(plist);
		plist = NULL;
	}

}

//头删
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;

}

//查找
SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

//在指定位置之前插⼊数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && pos);
	SLTNode* Newnode = BuyNode(x);
	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* priv = *pphead;
		while (priv->next != pos)
		{
			priv = priv->next;
		}
		priv->next = Newnode;
		Newnode->next = pos;

	}


}
//在指定位置之后插⼊数据
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* Newnode = BuyNode(x);
	Newnode->next = pos->next;
	pos->next = Newnode;
}

//删除pos结点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos);

	if (*pphead == pos)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* phead = *pphead;
		while (phead->next != pos)
		{
			phead = phead->next;
		}
		phead->next = phead->next->next;
		free(pos);
		pos = NULL;
	}


}
//删除pos之后的结点
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos && pos->next);
	SLTNode* next = pos->next;
	pos->next = next->next;
	free(next);
	next = NULL;

}

//销毁链表
void SListDestroy(SLTNode** pphead)
{
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		SLTNode* new = pcur->next;
		free(pcur);
		pcur = new;

	}
	*pphead = NULL;
}